/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-26 11:16:06
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-08 09:37:22
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/device_detail/device/device_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/data_type_config.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/device_obj/group_config_model.dart';
import 'package:yt_devops/model/slave_ems_network_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_item_model.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import 'device_model.dart';

class DeviceController extends BaseDetailController {
  DeviceServices deviceServices = Get.find();

  ///
  UseSubsribe subsribe = UseSubsribe();

  UseSubsribe? connectStatusSubsribe;

  Stream<Map<String, dynamic>>? dataStream;

  StreamController<Map<String, dynamic>>? streamController;

  StreamSubscription<Map<String, dynamic>>? connectionSubscription;

  /// 导航栏弹出层
  List<PopupMenuItem> actionList = [];

  ///渲染列表
  List<DeviceRealTimeModel> modelList = [];

  /// 设备详情
  DeviceModel? deviceModel;

  /// 设备id;
  late int deviceId;

  /// 从ems id列表
  List<int> salaveEmsIDs = [];

  /// 远程控制指令列表
  Map remotePage = {};

  /// 指令列表
  Map paramPage = {};

  /// 是否都单独一行展示
  bool isSingleLine = false;
  NewAirCoolingPageController newAirController = Get.find();
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() async {
    await connectionSubscription?.cancel();
    await streamController?.close();
    await subsribe.closeListen();
    await connectStatusSubsribe?.closeListen();
    super.onClose();
  }

  Future toService(value) async {
    Get.back();

    if (value == 0) {
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceId,
        'page': paramPage,
        'title': ResKey.parameterSets.tr
      });
    } else if (value == 1) {
      /// 远程控制
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceId,
        'page': remotePage,
        'title': ResKey.remoteControll.tr
      });
    }
  }

  getDeviceData() => Configs.httpClient.requestWithLoading(() async {
        var json = await DeviceServices().getDeviceInfo({'deviceId': deviceId});
        deviceModel = DeviceModel.fromJson(json);
        init(deviceModel!);
      });

  ///
  /// 获取物模型
  /// 订阅数据
  /// 如果是ems ， 则获取从ems列表，并订阅从ems在线状态
  ///
  init(DeviceModel model) async {
    /// ems 都单独一行展示
    isSingleLine = model.productType == ProductType.ems.value;
    await getOssPhysicalModel(model.productId!);
    streamController = subsribe.start([model.deviceId!], true);
    if (model.productType == ProductType.ems.value) {
      getEmsDevices().then((value) {
        if (salaveEmsIDs.isEmpty) {
          return;
        }
        connectStatusSubsribe = UseSubsribe(isContainDeviceId: true);
        connectionSubscription = connectStatusSubsribe
            ?.start(salaveEmsIDs, true, type: MessageEventType.networkStatus)
            .stream
            .listen((event) {
          // Log.d('从设备在线状态 $event');
          streamController?.add(event);
        });
      });
    }
  }

  /// 获取物模型
  /// id = runningData 设备详情
  /// id =  config 参数设置
  /// id = remoteControl 远程控制,
  Future getOssPhysicalModel(int productId) =>
      Configs.httpClient.requestWithLoading(
        () async {
          modelList.clear();
          actionList.clear();
          var result = await deviceServices
              .getDeviceNewProperty({'productId': productId, 'platform': 1});

          for (var res in result['data']) {
            if (res['id'] == 'runningData' || res['id'] == 'deviceDetail') {
              // List<GroupConfigModel> groupList = [];

              modelGroup(res);
              // groupList = List.generate(
              //     res['children'].length,
              //     (index) => GroupConfigModel.fromJson(res['children'][index])
              //       ..setChildren = res['children'][index]['children'] ?? []);
              //
              // // 对设备详情的分组进行处理
              // for (var group in groupList) {
              //   if (group.name == '接入设备列表') {
              //     /// 接入设备目前app不要求展示
              //     continue;
              //   }
              //   var properties = List.generate(
              //       group.children!.length,
              //       (index) => DetailItemModel(
              //           field: group.children![index]!['id'],
              //           label: group.children![index]['name'],
              //           format: (value) => FuncUtils.formatModelValue(
              //               value,
              //               DataTypeConfig.fromJson(
              //                   group.children![index]['dataType']))));
              //   modelList.add(DeviceRealTimeModel(
              //       groupName: group.name, items: properties));
              // }
            } else if (res['id'] == "config" &&
                !FuncUtils.isListEmpty(res['children']) &&
                deviceModel?.masterSlaveMode != MasterSlaveModeType.vice) {
              /// 参数配置
              paramPage = res;

              var pass = isAnyDetailAuthoritysPass(res['children']);

              if (pass) {
                /// 没有权限，则不展示按钮
                actionList.add(generatePopItem(
                    Image.asset(
                      ImageAssets.iconSetting,
                      fit: BoxFit.fill,
                    ),
                    ResKey.parameterSets.tr,
                    0));
              }
            } else if (res['id'] == "remoteControl" &&
                !FuncUtils.isListEmpty(res['children']) &&
                deviceModel?.masterSlaveMode != MasterSlaveModeType.vice) {
              /// 远程控制

              remotePage = res;

              var pass = isAnyDetailAuthoritysPass(res['children']);

              if (pass) {
                /// 没有权限，则不展示按钮
                actionList.add(generatePopItem(
                    Image.asset(
                      ImageAssets.iconRemoteControl,
                      fit: BoxFit.fill,
                    ),
                    ResKey.remoteControll.tr,
                    1));
              }
            }
          }

          update();
          // newAirController.setActionList(actionList);
        },
        onError: (p0) {
          print('error $p0');
          return true;
        },
        showLoading: false,
      );

  modelGroup(Map map) {
    List<GroupConfigModel> groupList = [];
    groupList = List.generate(
        map['children'].length,
        (index) => GroupConfigModel.fromJson(map['children'][index])
          ..setChildren = map['children'][index]['children'] ?? []);

    /// 对设备详情的分组进行处理
    for (var group in groupList) {
      if (group.name == '接入设备列表') {
        /// 接入设备目前app不要求展示
        continue;
      }
      var properties = List.generate(
          group.children!.length,
          (index) => DetailItemModel(
              field: group.children![index]!['id'],
              label: group.children![index]['name'],
              format: (value) => FuncUtils.formatModelValue(
                  value,
                  DataTypeConfig.fromJson(
                      group.children![index]['dataType']))));
      modelList
          .add(DeviceRealTimeModel(groupName: group.name, items: properties));
      update();
    }
  }

  PopupMenuItem generatePopItem(Widget icon, String title, value) {
    return PopupMenuItem(
      value: value,
      enabled: false,
      child: Row(
        children: [
          icon,
          Gaps.hGap10,
          Text(
            title,
            style: TextStyles.f14,
          ),
        ],
      ),
    );
  }

  /// 获取从ems列表
  Future getEmsDevices() async {
    try {
      var data = await deviceServices.getEmsDeviceNet({'deviceId': deviceId});
      List<DetailItemModel> itemModels = [];
      for (var i = 0; i < data.length; i++) {
        var slaveEmsNetworkModel = SlaveEmsNetworkModel.fromJson(data[i]);
        salaveEmsIDs.add(slaveEmsNetworkModel.deviceId!);
        itemModels.add(DetailItemModel(
            label:
                '${slaveEmsNetworkModel.deviceName}${ResKey.fromEmsCommunicationStatus.tr}',
            field: 'networkStatus-${slaveEmsNetworkModel.deviceId}',
            format: (int? value) => $enumDecode(
                    $ConnectStatusTypeEnumMap, value,
                    unknownValue: ConnectStatusType.unConfig)
                .label));
      }
      if (itemModels.isNotEmpty) {
        modelList.add(DeviceRealTimeModel(
            groupName: ResKey.fromEmsList.tr, items: itemModels));
      }

      update();
    } on ApiException catch (e) {
      showError(e.message);
    }
  }

  /// 鉴权
  bool isAnyDetailAuthoritysPass(List? group) {
    if (group == null) {
      return true;
    }
    List<String> detailAuthorityList = [];
    var list = FuncUtils.getPropFromTree(group,
        getKey: (item) => item['authority'],
        getChildren: (item) => item['children']);
    for (var element in list) {
      detailAuthorityList
          .addAll((element as List).map((e) => e['detail'] as String).toList());
    }

    var map = FuncUtils.authentication(authorityList: detailAuthorityList);
    return map['pass'];
  }
}
